package com.store.app.hyphenate;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.EaseAtMessageHelper;
import com.hyphenate.easeui.model.HyUserDao;
import com.hyphenate.easeui.model.recordBean_hy;
import com.hyphenate.easeui.ui.EaseBaseFragment;
import com.hyphenate.easeui.ui.EaseGroupRemoveListener;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.util.EMLog;
import com.opendanmaku.DanmakuItem;
import com.opendanmaku.DanmakuView;
import com.opendanmaku.IDanmakuItem;
import com.store.app.MainActivity;
import com.store.app.bean.HXUserBean;
import com.store.app.bean.LiveBean;
import com.store.app.http.Stores;
import com.store.app.imlife.bean.HxCmdBean;
import com.store.app.utils.http.MD5;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONObject;

import java.io.File;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * you can new an EaseChatFragment to use or you can inherit it to expand.
 * You need call setArguments to pass chatType and userId 
 * <br/>
 * <br/>
 * you can see ChatActivity in demo for your reference
 *
 */
public class EaseChatFragment_Live extends EaseBaseFragment implements EMMessageListener {
    protected static final String TAG = "EaseChatFragment";

    /**
     * params to fragment
     */
    protected Bundle fragmentArgs;
    protected int chatType;
    protected String toChatUsername;
    //聊天列表数据
    protected EMConversation conversation;

    protected Handler handler = new Handler();

    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;
    protected GroupListener groupListener;
    protected EMMessage contextMenuMessage;


    private EMChatRoomChangeListener chatRoomChangeListener;
    private boolean isMessageListInited;
    private DanmakuView mDanmakuView;
    //数据库存储
    private DBHelper_hy db=null;
    private recordBean_hy rb=null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(com.hyphenate.easeui.R.layout.ease_fragment_chat_live, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        fragmentArgs = getArguments();
        // check if single chat or group chat
        chatType = fragmentArgs.getInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_CHATROOM);
        // userId you are chat with or group id
        toChatUsername = fragmentArgs.getString(EaseConstant.EXTRA_USER_ID);
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * init view
     */
    protected void initView() {
        if(db==null){
            db=new DBHelper_hy(getActivity());
            rb=new recordBean_hy();
        }
        mDanmakuView = (DanmakuView) getView().findViewById(com.hyphenate.easeui.R.id.danmakuView);


    }

    protected void setUpView() {
        if (chatType == EaseConstant.CHATTYPE_SINGLE) {
            if(EaseUserUtils.getUserInfo(toChatUsername) != null){
            }

        } else {
            if (chatType == EaseConstant.CHATTYPE_GROUP) {
                //group chat
                EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
                if (group != null) {
                    groupListener = new GroupListener();
                    EMClient.getInstance().groupManager().addGroupChangeListener(groupListener);
                }
            } else {
                onChatRoomViewCreation();
            }

        }
        if (chatType != EaseConstant.CHATTYPE_CHATROOM) {
            onConversationInit();

        }




        // show forward message if the message is not null
        String forward_msg_id = getArguments().getString("forward_msg_id");
        if (forward_msg_id != null) {
            forwardMessage(forward_msg_id);
        }
    }




    protected void onConversationInit(){
        conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);
        conversation.markAllMessagesAsRead();
        // the number of messages loaded into conversation is getChatOptions().getNumberOfMessagesLoaded
        // you can change this number
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
        }
//        for(int i=0;i<msgs.size();i++){
//            EMMessage emMessage=msgs.get(i);
//            if(emMessage.getType() == EMMessage.Type.TXT){
//                // 设置内容
//                EMTextMessageBody txtBody = (EMTextMessageBody) emMessage.getBody();
//                Spannable span = EaseSmileUtils.getSmiledText(getActivity(), txtBody.getMessage());
////                SpannableString span = EaseSmileUtils.getSmiledText(getActivity(), txtBody.getMessage());
//                // 设置内容
//                IDanmakuItem item = new DanmakuItem(getActivity(),new SpannableString(span), mDanmakuView.getWidth(),0,android.R.color.white,17,1);
////                    IDanmakuItem item = new DanmakuItem(this, input, mDanmakuView.getWidth());
////                    item.setTextColor(getResources().getColor(R.color.my_item_color));
////                    item.setTextSize(14);
////                    item.setTextColor(textColor);
//                mDanmakuView.addItemToHead(item);
//            }
//        }
    }






    @Override
    public void onResume() {
        super.onResume();

        EaseUI.getInstance().pushActivity(getActivity());
        // register the event listener when enter the foreground
        EMClient.getInstance().chatManager().addMessageListener(this);

        if(chatType == EaseConstant.CHATTYPE_GROUP){
            EaseAtMessageHelper.get().removeAtMeGroup(toChatUsername);
        }
        mDanmakuView.show();
    }
    @Override
    public void onPause() {
        super.onPause();
        mDanmakuView.hide();
    }
    @Override
    public void onStop() {
        super.onStop();
        // unregister this event listener when this activity enters the
        // background
        EMClient.getInstance().chatManager().removeMessageListener(this);

        // remove activity from foreground activity list
        EaseUI.getInstance().popActivity(getActivity());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (groupListener != null) {
            EMClient.getInstance().groupManager().removeGroupChangeListener(groupListener);
        }

        if(chatType == EaseConstant.CHATTYPE_CHATROOM){
            EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
        }

        if(chatRoomChangeListener != null){
            EMClient.getInstance().chatroomManager().removeChatRoomChangeListener(chatRoomChangeListener);
        }
        mDanmakuView.clear();
    }



    protected void onChatRoomViewCreation() {
      //  final ProgressDialog pd = ProgressDialog.show(getActivity(), "", "");
        EMClient.getInstance().chatroomManager().joinChatRoom(toChatUsername, new EMValueCallBack<EMChatRoom>() {

            @Override
            public void onSuccess(final EMChatRoom value) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity().isFinishing() || !toChatUsername.equals(value.getId()))
                            return;
                        //   pd.dismiss();
//                        EMChatRoom room = EMClient.getInstance().chatroomManager().getChatRoom(toChatUsername);
//                        if (room != null) {
//                            titleBar.setTitle(room.getName());
//                            EMLog.d(TAG, "join room success : " + room.getName());
//                        } else {
//                            titleBar.setTitle(toChatUsername);
//                        }
                        addChatRoomChangeListenr();
                        onConversationInit();

                    }
                });
            }

            @Override
            public void onError(final int error, String errorMsg) {
                // TODO Auto-generated method stub
                EMLog.d(TAG, "join room failure : " + error);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new LiveBean(1));
                    }
                });
//                getActivity().finish();
            }
        });
    }


    protected void addChatRoomChangeListenr() {
        chatRoomChangeListener = new EMChatRoomChangeListener() {

            @Override
            public void onChatRoomDestroyed(String roomId, String roomName) {
                if (roomId.equals(toChatUsername)) {
                    showChatroomToast(" room : " + roomId + " with room name : " + roomName + " was destroyed");
                    getActivity().finish();
                }
            }

            @Override
            public void onMemberJoined(String roomId, String participant) {
                showChatroomToast("member : " + participant + " join the room : " + roomId);
            }

            @Override
            public void onMemberExited(String roomId, String roomName, String participant) {
                showChatroomToast("member : " + participant + " leave the room : " + roomId + " room name : " + roomName);
            }

            @Override
            public void onRemovedFromChatRoom(String s, String s1, String s2) {

            }

            @Override
            public void onMuteListAdded(String s, List<String> list, long l) {

            }

            @Override
            public void onMuteListRemoved(String s, List<String> list) {

            }

            @Override
            public void onAdminAdded(String s, String s1) {

            }

            @Override
            public void onAdminRemoved(String roomId, String participant) {
                if (roomId.equals(toChatUsername)) {
                    String curUser = EMClient.getInstance().getCurrentUser();
                    if (curUser.equals(participant)) {
                        EMClient.getInstance().chatroomManager().leaveChatRoom(toChatUsername);
                        getActivity().finish();
                    }else{
                        showChatroomToast("member : " + participant + " was kicked from the room : " + roomId );
                    }
                }
            }

            @Override
            public void onOwnerChanged(String s, String s1, String s2) {

            }

            @Override
            public void onAnnouncementChanged(String s, String s1) {

            }

        };

        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);
    }


    protected void showChatroomToast(final String toastContent){
//        getActivity().runOnUiThread(new Runnable() {
//            public void run() {
//               // Toast.makeText(getActivity(), toastContent, Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    // implement methods in EMMessageListener
    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        for (EMMessage message : messages) {

//
            String username = null;
            // group message
            if (message.getChatType() == ChatType.GroupChat || message.getChatType() == ChatType.ChatRoom) {
                username = message.getTo();
            } else {
                // single chat message
                username = message.getFrom();
            }

            // if the message is for current conversation
           if (username.equals(toChatUsername)) {

                //EaseUI.getInstance().getNotifier().vibrateAndPlayTone(message);
                if(message.getType() == EMMessage.Type.TXT) {
                    EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
                    HyUserDao hyUserDao = rb.findMember_other(db, message.getFrom());
                    if (hyUserDao == null) {
                        getUserNickname(message.getFrom(), txtBody.getMessage());
                    } else {
                        String s_nickname=hyUserDao.getNickname();
                        String s_mes="";
                        if(!TextUtils.isEmpty(s_nickname)){
                            s_mes=s_nickname+" : "+ txtBody.getMessage();
                        }else{
                            s_mes=txtBody.getMessage();
                        }
                        Spannable span = EaseSmileUtils.getSmiledText(getActivity(), s_mes);
                        // 设置内容
                        IDanmakuItem item = new DanmakuItem(getActivity(), new SpannableString(span), mDanmakuView.getWidth(), 0, android.R.color.white, 17, 1);
//                    IDanmakuItem item = new DanmakuItem(this, input, mDanmakuView.getWidth());
//                    item.setTextColor(getResources().getColor(R.color.my_item_color));
//                    item.setTextSize(14);
//                    item.setTextColor(textColor);
                        mDanmakuView.addItemToHead(item);
                    }
                }
            }
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        for (EMMessage message : messages) {
            String username = null;
            // group message
            if (message.getChatType() == ChatType.GroupChat || message.getChatType() == ChatType.ChatRoom) {
                username = message.getTo();
            } else {
                // single chat message
                username = message.getFrom();
            }
            if(username.equals(toChatUsername)) {
                EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                String action = cmdMsgBody.action();//获取自定义action
                EventBus.getDefault().post(new HxCmdBean(action));
            }
        }
    }

    @Override
    public void onMessageRead(List<EMMessage> list) {

    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {

    }



    @Override
    public void onMessageChanged(EMMessage emMessage, Object change) {

    }




    //send message
    protected void sendTextMessage(String content) {
        if(EaseAtMessageHelper.get().containsAtUsername(content)) {
            sendAtMessage(content);
        }else{
            EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
            sendMessage(message);
        }
    }

    /**
     * send @ message, only support group chat message
     * @param content
     */
    private void sendAtMessage(String content){
        if(chatType != EaseConstant.CHATTYPE_GROUP){
            EMLog.e(TAG, "only support group chat message");
            return;
        }
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUsername);
        EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
        if(EMClient.getInstance().getCurrentUser().equals(group.getOwner()) && EaseAtMessageHelper.get().containsAtAll(content)){
            message.setAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG, EaseConstant.MESSAGE_ATTR_VALUE_AT_MSG_ALL);
        }else {
            message.setAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG,
                    EaseAtMessageHelper.get().atListToJsonArray(EaseAtMessageHelper.get().getAtMessageUsernames(content)));
        }
        sendMessage(message);

    }


    protected void sendBigExpressionMessage(String name, String identityCode){
        EMMessage message = EaseCommonUtils.createExpressionMessage(toChatUsername, name, identityCode);
        sendMessage(message);
    }

    protected void sendImageMessage(String imagePath) {
        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, toChatUsername);
        sendMessage(message);
    }




    protected void sendMessage(EMMessage message){
        if (message == null) {
            return;
        }
        if(chatFragmentHelper != null){
            //set extension
            chatFragmentHelper.onSetMessageAttributes(message);
        }
        if (chatType == EaseConstant.CHATTYPE_GROUP){
            message.setChatType(ChatType.GroupChat);
        }else if(chatType == EaseConstant.CHATTYPE_CHATROOM){
            message.setChatType(ChatType.ChatRoom);
        }
        //send message
        EMClient.getInstance().chatManager().sendMessage(message);
        //refresh ui
        if(isMessageListInited) {

        }
    }




    /**
     * forward message
     *
     * @param forward_msg_id
     */
    protected void forwardMessage(String forward_msg_id) {
        final EMMessage forward_msg = EMClient.getInstance().chatManager().getMessage(forward_msg_id);
        EMMessage.Type type = forward_msg.getType();
        switch (type) {
        case TXT:
            if(forward_msg.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)){
                sendBigExpressionMessage(((EMTextMessageBody) forward_msg.getBody()).getMessage(),
                        forward_msg.getStringAttribute(EaseConstant.MESSAGE_ATTR_EXPRESSION_ID, null));
            }else{
                // get the content and send it
                String content = ((EMTextMessageBody) forward_msg.getBody()).getMessage();
                sendTextMessage(content);
            }
            break;
        case IMAGE:
            // send image
            String filePath = ((EMImageMessageBody) forward_msg.getBody()).getLocalUrl();
            if (filePath != null) {
                File file = new File(filePath);
                if (!file.exists()) {
                    // send thumb nail if original image does not exist
                    filePath = ((EMImageMessageBody) forward_msg.getBody()).thumbnailLocalPath();
                }
                sendImageMessage(filePath);
            }
            break;
        default:
            break;
        }

        if(forward_msg.getChatType() == ChatType.ChatRoom){
            EMClient.getInstance().chatroomManager().leaveChatRoom(forward_msg.getTo());
        }
    }

    /**
     * listen the group event
     * 
     */
    class GroupListener extends EaseGroupRemoveListener {



        @Override
        public void onUserRemoved(final String groupId, String groupName) {
            getActivity().runOnUiThread(new Runnable() {

                public void run() {
                    if (toChatUsername.equals(groupId)) {
                        Toast.makeText(getActivity(), com.hyphenate.easeui.R.string.you_are_group, Toast.LENGTH_SHORT).show();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                EventBus.getDefault().post(new LiveBean(1));
                            }
                        });
                    }
                }
            });
        }

        @Override
        public void onGroupDestroyed(final String groupId, String groupName) {
        	// prompt group is dismissed and finish this activity
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (toChatUsername.equals(groupId)) {
                        Toast.makeText(getActivity(), com.hyphenate.easeui.R.string.the_current_group, Toast.LENGTH_SHORT).show();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                EventBus.getDefault().post(new LiveBean(1));
                            }
                        });
                    }
                }
            });
        }

    }
    
   
    protected EaseChatFragmentHelper chatFragmentHelper;
    public void setChatFragmentListener(EaseChatFragmentHelper chatFragmentHelper){
        this.chatFragmentHelper = chatFragmentHelper;
    }
    
    public interface EaseChatFragmentHelper{
        /**
         * set message attribute
         */
        void onSetMessageAttributes(EMMessage message);

        /**
         * enter to chat detail
         */
        void onEnterToChatDetails();
        
        /**
         * on avatar clicked
         * @param username
         */
        void onAvatarClick(String username);
        
        /**
         * on avatar long pressed
         * @param username
         */
        void onAvatarLongClick(String username);
        
        /**
         * on message bubble clicked
         */
        boolean onMessageBubbleClick(EMMessage message);
        
        /**
         * on message bubble long pressed
         */
        void onMessageBubbleLongClick(EMMessage message);
        
        /**
         * on extend menu item clicked, return true if you want to override
         * @param view 
         * @param itemId 
         * @return
         */
        boolean onExtendMenuItemClick(int itemId, View view);
        
        /**
         * on set custom chat row provider
         * @return
         */
        EaseCustomChatRowProvider onSetCustomChatRowProvider();
    }
    //调接口查询用户资料 （非反射回调）
    public void getUserNickname(String im_user_id, final String message){
        AjaxParams params = new AjaxParams();
        params.put("user_token", MainActivity.user_token);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("im_user_id", im_user_id);
        } catch (Exception e) {
        }
        params.put("params", jsonObject.toString());
        params.put("service", "chat.getIMUserDetail");
        params.put("sign", genPackageSignUser(params));
        FinalHttp fh = new FinalHttp();
        fh.post( Stores.http+"/openapi/community", params, new AjaxCallBack(){
            @Override
            public void onLoading(long count, long current) {
            }
            @Override
            public void onSuccess(Object t) {
                String result = t.toString();
                Log.i("mylog",result+"ee");
                String s_nickname="";
                try {

                try {
                    JSONObject jsonObject1=new JSONObject(result);
                    result=jsonObject1.getJSONObject("data").toString();
                    Gson gson = new Gson();
                    HXUserBean hxUserBean = gson.fromJson(result, HXUserBean.class);
                    rb.saveMember(db, "", hxUserBean.getIm_user_id(), hxUserBean.getNickname()
                            , "", hxUserBean.getHead_pic_path(), "0");
                    s_nickname=hxUserBean.getNickname();
                }catch (Exception e){
                }


                String s_mes="";
                if(!TextUtils.isEmpty(s_nickname)){
                    s_mes=s_nickname+" : "+ message;
                }else{
                    s_mes=message;
                }
                Spannable span = EaseSmileUtils.getSmiledText(getActivity(), s_mes);
                // 设置内容
                IDanmakuItem item = new DanmakuItem(getActivity(), new SpannableString(span), mDanmakuView.getWidth(), 0, android.R.color.white, 17, 1);
//                    IDanmakuItem item = new DanmakuItem(this, input, mDanmakuView.getWidth());
//                    item.setTextColor(getResources().getColor(R.color.my_item_color));
//                    item.setTextSize(14);
//                    item.setTextColor(textColor);
                mDanmakuView.addItemToHead(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }
    public String genPackageSignUser(AjaxParams params) {
        if (!getActivity().isFinishing()) {
            if (TextUtils.isEmpty(MainActivity.user_security_code)) {
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity() );
                MainActivity.user_security_code = preferences.getString("user_security_code", "");
//                ToastUtils.showTextToast(context,"user_security_code丢失");
            }
        }
        String paramString = params.toString();
        List<String> sortList = new ArrayList<>();
//        Log.v("zyl", "加密前：" + paramString);
        String[] arrs = paramString.split("&");
        for (int i = 0; i < arrs.length; i++) {
            sortList.add(arrs[i] + "&");
        }
        Collections.sort(sortList, Collator.getInstance(java.util.Locale.CHINA));
        String signStr = "";
        for (String s : sortList) {
            signStr += s;
        }
        signStr = signStr.toString().substring(0, signStr.toString().length() - 1);
        signStr += MainActivity.user_security_code;
//        Log.v("zyl","MainActivity.user_security_cod："+MainActivity.user_security_code);
//        Log.v("zyl","加密前2："+signStr);

        String packageSign = MD5.getMessageDigest(signStr.getBytes());
        return packageSign;
    }
}
